package com.xiaxiang.xiawan.Effect;

import android.content.Intent;
import android.os.Bundle;

import com.dg.acb.utils.configdata.XXConstants;
import com.donggua.aichebao.commonui.customtablayout.TabLayout;

import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;

import com.xiaxiang.xiawan.Effect.Adapter.EffectData;
import com.xiaxiang.xiawan.Effect.Adapter.EffectPagerAdapter;
import com.xiaxiang.xiawan.FragmentBase;
import com.xiaxiang.xiawan.R;
import com.xiaxiang.xiawan.Ui.WaitDialog;
import com.xiaxiang.xiawan.Util.FileUtil;
import com.xiaxiang.xiawan.Util.HttpDownloader;
import com.xiaxiang.xiawan.Util.XXToolUtil;
import com.xiaxiang.xiawan.XXConfigData;
import com.xiaxiang.xiawan.task.DownloadEffectTask;
import com.xiaxiang.xiaxwan.ar.data.XXARMaterialVideoData;
import com.xx.xiawan.net.DGJsonResult;
import com.xx.xiawan.net.DGRequestListener;
import com.xx.xiawan.net.GetRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by mk on 2017/10/17.
 */

public class EffectFragment extends FragmentBase implements View.OnClickListener {
    public static final String URL = XXConstants.HTTP_GET_EFFECT_MATERIAL_LIST_BY_CATEGRY_ID;
    private View view;
    private TabLayout effect_tablayout;
    private List<View> viewList;
    private  String tabText[] = {"搞怪  ", "神力  ", "互怼  "};
    private ViewPager effect_view_page;
    private EffectPagerAdapter adapter;
    private ARMediaOperator mARMediaOperator;
    private ArrayList<EffectView> mEffectViewList;
    private Handler mUiHandler;
    private int[] mTabIdList = null;
    private static final int INIT_PAGEVIEW = 0;
    private static final int INIT_TAB = 1;
    private int mSelectTabIndex = 0;
    private Button mBtnEffect;
    private WaitDialog mWaitDialog;
    private DownloadEffectTask mDownloadEffectTask;
    private boolean mIsInitPageList[] = null;
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.effect_fragment, container, false);
        setUiHandler();
        mARMediaOperator = new ARMediaOperator(view,getActivity());
        mWaitDialog = new WaitDialog(this.getActivity());
        get();
        showWaitDialog();
        mDownloadEffectTask = new DownloadEffectTask(getActivity(),mUiHandler);
        mDownloadEffectTask.start();
        //getNetInfomation();
        ((TextView)view.findViewById(R.id.TitleBarText)).setText("特效");
        return view;
    }

    private void showWaitDialog(){
        mWaitDialog.showDialog();
    }

    private void closeWaitDialog(){
        mWaitDialog.closeDialog();
    }
    private void setUiHandler(){
        mUiHandler = new Handler(){
          public void handleMessage(Message msg){
              super.handleMessage(msg);
              switch (msg.what){
                  case  INIT_PAGEVIEW:
                      initView();
                      initViewPager();
                      getNetInfomation(0);
                      break;
                  case INIT_TAB:
                      closeWaitDialog();
                      ArrayList<EffectData> effectDataList = (ArrayList<EffectData>)msg.obj;
                      EffectView effectView1 = mEffectViewList.get(mSelectTabIndex);
                      for(int i=0;i<effectDataList.size();i++){
                          effectView1.addEffectData(effectDataList.get(i));
                      }
                      if(effectDataList.size() > 0){
                          effectView1.simulationOnItemClick();
                          mBtnEffect.setEnabled(true);
                      }else{
                          mBtnEffect.setEnabled(false);
                      }
                      mIsInitPageList[mSelectTabIndex] = true;
                      break;
                  case DownloadEffectTask.START_SHOW:
                      closeWaitDialog();
                      mBtnEffect.setEnabled(true);
                      String materialName = (String)msg.obj;
                      Intent intent = new Intent("com.xiaxiang.xiawan.ar.camera");
                      intent.setPackage(getActivity().getPackageName());
                      EffectView effectView = mEffectViewList.get(mSelectTabIndex);
                      EffectData effectData = effectView.getSelectEffectData();
                      XXARMaterialVideoData data = new XXARMaterialVideoData();
                      data.mVideoPath = "";
                      data.setNeedVideoPath(false);
                      data.mMaterialId = effectData.mEffectId;
                      data.mMaterialUrl = effectData.mEffectUrl;
                      data.mUserName = "";
                      data.mName = effectData.mEffectName;
                      data.mMaterialPathName = materialName;
                      data.mArMode =  1;
                      intent.putExtra(XXToolUtil.AR_MODE_KEY, 1);
                      intent.putExtra(XXToolUtil.MATERIAL_VIDEO_DATA_KEY,data);
                      intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                      startActivity(intent);
                      break;
                  case DownloadEffectTask.SHOW_DIALOG:
                      showWaitDialog();
                      break;
                  case DownloadEffectTask.ERROR:
                      closeWaitDialog();
                      if(mBtnEffect != null){
                          mBtnEffect.setEnabled(true);
                      }
                      XXToolUtil.showTip(getActivity(),(String)msg.obj);
                      break;
              }


          }
        };
    }
    private void get(){
        String url =  XXConstants.HTTP_GET_EFFECT_MATERIAL_CATEGORY_LIST;
        DGRequestListener listener = new DGRequestListener(){
            @Override
            public void onSuccess(DGJsonResult result) {
                Log.e("get"," get url is "+result.result);
                try {
                    JSONArray array  = new JSONArray(result.result);
                    int size = array.length();
                    Log.e("get","size is "+size);
                    tabText = new String[size];
                    mTabIdList = new int[size];
                    mIsInitPageList = new boolean[size];
                    for(int i=0;i<size;i++){
                        mIsInitPageList[i] = false;
                        JSONObject jsonObject = array.getJSONObject(i);
                        tabText[i] = jsonObject.getString("name");
                        mTabIdList[i] = jsonObject.getInt("id");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mUiHandler.sendEmptyMessage(INIT_PAGEVIEW);
            }

            @Override
            public void onError(String error) {
                //mUiHandler.sendEmptyMessage(ERROR);
                sendErrorMsg(error);
            }
        };
        GetRequest getRequest = new GetRequest(url,this.getActivity().getApplicationContext(),listener);
        getRequest.startNoLock();
    }
    private void initView() {
        mBtnEffect = (Button)view.findViewById(R.id.btn_effect);
        mBtnEffect.setEnabled(false);
        mBtnEffect.setOnClickListener(this);
        initTabLayout();

    }

    private static String getUrl(int pageNo,int pageSize ,int id){
        StringBuilder builder = new StringBuilder();
        String dy = "=";
        String a = "&";
        builder.append(URL);
        builder.append("?");
        builder.append("pageNo");
        builder.append(dy);
        builder.append(pageNo);
        builder.append(a);
        builder.append("pageSize");
        builder.append(dy);
        builder.append(pageSize);
        builder.append(a);
        builder.append("categryId");
        builder.append(dy);
        builder.append(id);
        return builder.toString();


    }
    private void getNetInfomation(final int idIndex){
        String url = getUrl(1,20,mTabIdList[idIndex]);
        mBtnEffect.setEnabled(false);
        DGRequestListener listener = new DGRequestListener(){

            @Override
            public void onSuccess(DGJsonResult result) {
               // EffectView effectView = mEffectViewList.get(idIndex);
                try {
                    JSONObject json = new JSONObject(result.result);
                    int size = json.getInt("total");
                    JSONArray array = json.getJSONArray("rows");
                    ArrayList<EffectData> effectDataList = new ArrayList<EffectData>(size);
                    int len = array.length();
                    for(int i = 0;i < len;i++){
                        JSONObject object = array.getJSONObject(i);
                        EffectData effectData = new EffectData();
                        effectData.mEffectIndex = idIndex;
                        effectData.setObjectData(object);
                        effectDataList.add(effectData);
                        //effectView.addEffectData(effectData);
                    }
                    Message msg = mUiHandler.obtainMessage();
                    msg.what = INIT_TAB;
                    msg.obj = effectDataList;
                    mUiHandler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String error) {
                //mUiHandler.sendEmptyMessage(ERROR);
                sendErrorMsg(error);
            }
        };
        GetRequest getRequest = new GetRequest(url,this.getActivity().getApplicationContext(),listener);
        getRequest.startNoLock();
    }

    private void initTabLayout() {
        effect_tablayout = (TabLayout) view.findViewById(R.id.effect_tablayout);
        effect_tablayout.setTabMode(TabLayout.MODE_FIXED);
        for(int i=0;i<tabText.length;i++){
            effect_tablayout.addTab(effect_tablayout.newTab().setText(tabText[i]));
        }
        TabLayout.Tab tab = effect_tablayout.getTabAt(0);
        final View  view  = tab.getTabViewTextView();
        view.post(new Runnable() {
            @Override
            public void run() {
                int width = view.getWidth();
                effect_tablayout.setLineWidth(width);
            }
        });
    }

    private void initViewPager() {
        viewList = new ArrayList<View>();
        effect_view_page = (ViewPager) view.findViewById(R.id.effect_view_page);
        mEffectViewList = new ArrayList<EffectView>();
        for(int i=0;i<tabText.length;i++){
            EffectView effectView = new EffectView(getActivity(),mARMediaOperator);
            effectView.initTextView(view);
            mEffectViewList.add(effectView);
            viewList.add(effectView.getView());
        }
        adapter = new EffectPagerAdapter(viewList, tabText);
        effect_view_page.setAdapter(adapter);
        effect_tablayout.setupWithViewPager(effect_view_page);
        ViewPager.OnPageChangeListener listener = new ViewPager.OnPageChangeListener(){

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mSelectTabIndex = position;
                if(!mIsInitPageList[position]){
                    getNetInfomation(position);
                }else{
                    EffectView effectView = mEffectViewList.get(mSelectTabIndex);
                    int size = effectView.getEffectDataListSize();
                    if(size > 0){
                        mBtnEffect.setEnabled(true);
                    }
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        };
        effect_view_page.setOnPageChangeListener(listener);
    }


    @Override
    public void onPause() {
        super.onPause();
        mARMediaOperator.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        mARMediaOperator.onResume();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mARMediaOperator.onDestroy();
        mDownloadEffectTask.quitThread();
    }

    public void onClick(View view) {
        //跳转
        int id = view.getId();
        if(id == R.id.btn_effect){
            if(isLogin()){
                view.setEnabled(false);
                EffectView effectView = mEffectViewList.get(mSelectTabIndex);
                EffectData effectData = effectView.getSelectEffectData();
                if(effectData != null){
                    mDownloadEffectTask.startDownload(effectData.mEffectUrl,effectData.mMd5);
                }
            }else{
                view.setEnabled(false);
                startLoginActivity();
            }
        }

    }
    private void sendErrorMsg(String text){
        Message msg = mUiHandler.obtainMessage();
        msg.what = DownloadEffectTask.ERROR;
        msg.obj = text;
        mUiHandler.sendMessage(msg);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            mARMediaOperator.onPause();
        }else{
            mARMediaOperator.onResume();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == XXConfigData.LOGIN_REQUEST_CODE){
            if(requestCode == XXConfigData.LOGIN_RECODE_SUCCESS){
                mMainActivity.initUserInfo();
                EffectView effectView = mEffectViewList.get(mSelectTabIndex);
                EffectData effectData = effectView.getSelectEffectData();
                mDownloadEffectTask.startDownload(effectData.mEffectUrl,effectData.mMd5);
            }else{
                mBtnEffect.setEnabled(true);
            }
        }
    }
}
